package com.edgar.download.ui;

import android.os.Bundle;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.edgar.download.R;
import com.edgar.download.Download;
import com.edgar.download.DownloadManager;
import com.edgar.download.IDownloadListener;

/**
 * Created by xiexiang on 2015/10/31.
 */
public class DownloadTestActivity extends AppCompatActivity implements IDownloadListener{

    private static final ArrayMap<String,String> MAP = new ArrayMap<>();
    static {
        MAP.put("http://down.360safe.com/360mobilemgr/360box_web.apk","360box_web.apk");
        MAP.put("http://sqdd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk","mobileqq_android.apk");
    }
    private DownloadManager mDownloadManager;
    private View mRootView;
    private Button mBtnDownload;
    private Button mBtnDownload1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDownloadManager = DownloadManager.getInstance();
        mDownloadManager.registerDownloadListener(MAP.keyAt(0), this);
        mDownloadManager.registerDownloadListener(MAP.keyAt(1), this);
        setContentView(R.layout.download);
        mRootView = findViewById(R.id.download_root_layout);
        mBtnDownload = (Button) findViewById(R.id.btn_download);
        mBtnDownload1 = (Button) findViewById(R.id.btn_download1);

        mBtnDownload.setTag(0);
        mBtnDownload1.setTag(1);
    }

    public void onClick(View view){
        int index = (int)view.getTag();
        Download download = Download.createDownload(MAP.keyAt(index),
                "",MAP.valueAt(index));
        mDownloadManager.addDownload(download);
    }

    private Button findButtonByUrl(String url){
        int index = MAP.indexOfKey(url);
        return (Button) mRootView.findViewWithTag(index);
    }

    @Override
    public void onStart(String url) {
        findButtonByUrl(url).setText("开始下载");
    }

    @Override
    public void onPause(String url) {
        findButtonByUrl(url).setText("下载暂停");
    }

    @Override
    public void onCancel(String url) {
        findButtonByUrl(url).setText("下载取消");
    }

    @Override
    public void onFailure(String url,int statusCode) {
        findButtonByUrl(url).setText("下载失败");
    }

    @Override
    public void onComplete(String url) {
        findButtonByUrl(url).setText("下载完成");
    }

    @Override
    public void onWaitDownload(String url) {

    }

    @Override
    public void onDownload(String url, int status, int progress) {
        findButtonByUrl(url).setText("progress:"+progress);
    }
}